package com.heima.admin.service.Imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.LoginMapper;
import com.heima.admin.service.LoginService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dto.AdUserDTO;
import com.heima.model.admin.pojo.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.sql.Wrapper;
import java.util.Date;
import java.util.HashMap;

@Service
public class LoginServiceImp extends ServiceImpl<LoginMapper, AdUser> implements LoginService {
    @Override
    public ResponseResult loginIn(AdUserDTO adUserDTO) {
        //1.校验参数
        if (StringUtils.isBlank(adUserDTO.getName()) || StringUtils.isBlank(adUserDTO.getPassword())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"用户名密码不能为空!");
        }
        //根据用户名获取参数
        LambdaQueryWrapper<AdUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AdUser::getName, adUserDTO.getName());
        //根据自定义条件查询
        AdUser adUser = getOne(wrapper);
        //2.查询数据库是否存在该用户 存在
        if (adUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该用户名不存在!");
        }
        //3.对比密码是否一致  MD5加密（password+salt）
        String dbPassword = adUser.getPassword();
        String salt = adUser.getSalt();
        //转换
        String nowPassword = DigestUtils.md5DigestAsHex((adUserDTO.getPassword() + salt).getBytes());
        if (!dbPassword.equals(nowPassword)) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户名或密码错误!");
        }
        //4.更新时间
        adUser.setCreatedTime(new Date());
        updateById(adUser);
        //5.生成令牌 将用户的id放进去
        long id = (long)adUser.getId();
        AdUserVO adUserVO = new AdUserVO();
        //bean工具类将属性拷过来
        BeanUtils.copyProperties(adUser,adUserVO);

        adUserVO.setCreatedTime(adUser.getCreatedTime());
        //创建令牌
        String token = AppJwtUtil.getToken(id);
        //生成响应数据需要的格式
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",adUserVO);

        return ResponseResult.okResult(map);
    }
}

